
#django-filter插件过滤类
from django_filters.filterset import FilterSet
from . import models
from django_filters import filters
class CourseFilterSet(FilterSet):
    # field_name为类里面的字段名,lookup_expr用来设置过滤规则，gte是大于等于/gt是大于
    min_price = filters.NumberFilter(field_name='price',lookup_expr='gte')
    max_price = filters.NumberFilter(field_name='price',lookup_expr='lte')
    class Meta:
        model = models.Course
        # 如果过滤条件仅仅就是Model已有字段，方式一更好
        # 但方式二可以自定义过滤字段
        fields = ['course_category','min_price','max_price']





# 前台接口 :/course/free/?count=2 ,代表只对前台返回2条数据
class CountFilter:
    def filter_queryset(self, request, queryset, view):
        count = request.query_params.get('count', None)
        try:
            # TODO: 切片后的queryset不能再做ORM Q查询，如何实现queryset切片，现在再过滤时后配置
            # 结论：drf的搜索组件和排序组件都是建立在表的所有数据基础上的过滤规则，所以该自定义过滤类在视图类配置中
            # filter_backends = [SearchFilter, OrderingFilter, CountFilter] 必须在前两者之后
            return queryset[:int(count)]
        except:
            return queryset
